import { BadRequestException } from '@nestjs/common';
import { validate } from 'class-validator';

export const validateParams = async (data: any) => {
  const config = {
    whitelist: false,
    forbidNonWhitelisted: false,
    stopAtFirstError: true,
    skipMissingProperties: false,
  };
  const errors = await validate(data, config);

  if (errors.length > 0) {
    const err: any = errors[0] || {},
      constraints = Object.keys(err?.constraints || {}).map(
        (key) => (err?.constraints || {})[key] || '',
      );

    throw new BadRequestException(`${constraints}`);
  }

  return data;
};

export const formatDates = (data: any): any => {
  if (data instanceof Date) {
    const year = data.getFullYear();
    const month = String(data.getMonth() + 1).padStart(2, '0');
    const day = String(data.getDate()).padStart(2, '0');
    const hours = String(data.getHours()).padStart(2, '0');
    const minutes = String(data.getMinutes()).padStart(2, '0');
    const seconds = String(data.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }

  if (Array.isArray(data)) {
    return data.map((item) => formatDates(item));
  }

  if (typeof data === 'object' && data !== null) {
    const formattedData: any = {};
    for (const key of Object.keys(data)) {
      formattedData[key] = formatDates(data[key]);
    }
    return formattedData;
  }

  return data;
};
